package cn.b.sky.shop.activiti;

/*
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */

import cn.b.sky.shop.activiti.cmd.BpmnParseCmd;
import cn.b.sky.shop.activiti.cmd.SyncProcessModelCmd;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.editor.language.json.converter.BpmnJsonConverter;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.activiti.engine.impl.util.IoUtil;
import org.activiti.engine.impl.util.io.InputStreamSource;
import org.activiti.engine.repository.Model;
import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.resource.Put;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

/**
 * @author Tijs Rademakers
 */
public class MyModelSaveRestResource extends ServerResource implements ModelDataJsonConstants {

  private static final Logger LOGGER = LoggerFactory.getLogger(MyModelSaveRestResource.class);

  @Put
  public void saveModel(Form modelForm) {
    ObjectMapper objectMapper = new ObjectMapper();
    String modelId = (String) getRequest().getAttributes().get("modelId");
    // //System.out.println("json " + modelForm.getFirstValue("json_xml"));

    try {

      /*
       * ObjectNode modelNode = (ObjectNode)
       * objectMapper.readTree(modelForm.getFirstValue("json_xml"));
       * JsonToBpmnExport converter = new JsonToBpmnExport(modelNode);
       * byte[] bpmnBytes = converter.convert();
       * //System.out.println("bpmn " + new String(bpmnBytes));
       */

      RepositoryService repositoryService = ProcessEngines.getDefaultProcessEngine().getRepositoryService();
      Model model = repositoryService.getModel(modelId);

      ObjectNode modelJson = (ObjectNode) objectMapper.readTree(model.getMetaInfo());

      modelJson.put(MODEL_NAME, modelForm.getFirstValue("name"));
      modelJson.put(MODEL_DESCRIPTION, modelForm.getFirstValue("description"));
      model.setMetaInfo(modelJson.toString());
      model.setName(modelForm.getFirstValue("name"));

      repositoryService.saveModel(model);
      byte[] bytes = modelForm.getFirstValue("json_xml").getBytes("utf-8");
      repositoryService.addModelEditorSource(model.getId(), bytes);

      ObjectNode modelNode = (ObjectNode) new ObjectMapper().readTree(repositoryService.getModelEditorSource(model
          .getId()));

      BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(modelNode);

      byte[] bpmnBytes = new BpmnXMLConverter().convertToXML(bpmnModel);
      ByteArrayInputStream inputStream = new ByteArrayInputStream(bpmnBytes);

      ProcessEngineConfigurationImpl pconf = (ProcessEngineConfigurationImpl) ProcessEngines.getDefaultProcessEngine()
          .getProcessEngineConfiguration();
      bpmnModel = pconf.getManagementService().executeCommand(
          new BpmnParseCmd(new InputStreamSource(inputStream), true, true));

      byte[] diagramBytes = IoUtil.readInputStream(
          pconf.getProcessDiagramGenerator().generateDiagram(bpmnModel, "png",
              pconf.getProcessEngineConfiguration().getActivityFontName(), pconf.getLabelFontName(),
              pconf.getProcessEngineConfiguration().getClassLoader()), null);
      /*
       * InputStream svgStream = new
       * ByteArrayInputStream(modelForm.getFirstValue
       * ("svg_xml").getBytes("utf-8")); TranscoderInput input = new
       * TranscoderInput(svgStream);
       * 
       * PNGTranscoder transcoder = new PNGTranscoder(); // Setup output
       * ByteArrayOutputStream outStream = new ByteArrayOutputStream();
       * TranscoderOutput output = new TranscoderOutput(outStream);
       * 
       * // Do the transformation transcoder.transcode(input, output);
       * final byte[] result = outStream.toByteArray();
       */
      repositoryService.addModelEditorSourceExtra(model.getId(), diagramBytes);
      // outStream.close();
      //保存模型时候写入用户等相关属性
      pconf.getManagementService().executeCommand(
          new SyncProcessModelCmd(model.getId(), model.getKey(), model.getTenantId()));
    } catch (Exception e) {
      LOGGER.error("Error saving model", e);
      setStatus(Status.SERVER_ERROR_INTERNAL);
    }
  }
}
